package cn.yuhh.api.v1.user;

import cn.yuhh.api.exception.ApiException;
import cn.yuhh.api.helper.IDataToMap;
import cn.yuhh.api.helper.ApiResponse;
import cn.yuhh.api.service.AbstractApiService;
import cn.yuhh.core.domain.User;
import cn.yuhh.core.type.ResponseHeader;
import cn.yuhh.core.util.DigestUtils;
import cn.yuhh.core.util.UUIDGenerator;
import com.magic.spring.mongo.Mongo;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author ysw
 * @create 2020-02-17 16:31
 * @descreption
 **/
@Component("userLogin1.0")
public class UserLoginService extends AbstractApiService {
    @Override
    public Map service(Map request) {
        String tel = string(request, "tel");
        String password = string(request, "password");
        User user = Mongo.buildMongo().eq("tel", tel).findOne(User.class);
        if(user == null ){
            throw new ApiException(ResponseHeader.LOGIN_AUTHORIZED);
        }
        if(!DigestUtils.MD5(password).equals(user.getPassword())){
            throw new ApiException(ResponseHeader.NOT_AUTHORIZED);
        }
        String sessionId = UUIDGenerator.uuid();
        sessionManager.put(user.getId(), sessionId);
        //redis
        return ApiResponse.success(user, new IDataToMap<User>() {
            @Override
            public void dataToMap(Map map, User source) {
                map.put("name", source.getName());
                map.put("id", source.getId());
                map.put("sessionId", sessionId);
                map.put("role", user.getRole());
            }
        });
    }
}